package com.lizardmind.haofudoctor.ui.diagnosis.sickMan.advisory.kaifang.addChuFang

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.other.ChooseMedicineBean
import kotlinx.android.synthetic.main.item_choose_medicine.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * Created by Administrator on 2017/11/20.
 *
 */
class ChooseMedicineAdapter(val context: Context,
                            val list: ArrayList<ChooseMedicineBean>)
    : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val windowWidth:Int = context.resources.displayMetrics.widthPixels

    override fun getItemCount(): Int {
        return  list.size
    }

    private var itemPointClick:OnItemPointClick?=null

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        holder as MHolder
        holder.apply {
            itemView.tvChooseMedicineNameTag.text=list[position].tag
            val gridLayout=itemView.glChooseMedicine
            gridLayout.removeAllViews()

            for (i in 0 until list[position].listMedicine.size){
                val textview= TextView(context)
                textview.width=(windowWidth-dp2px(13+13))/3
                textview.gravity=Gravity.CENTER
                textview.setBackgroundResource(if ((i+1)%3==0) R.drawable.tv_bg_choose_medicine_end else R.drawable.tv_bg_choose_medicine)
                textview.setPadding(0,dp2px(13),0,dp2px(13))
                textview.text=list[position].listMedicine[i].title
                gridLayout.addView(textview)
                textview.onClick {
                    if (itemPointClick!=null)
                        itemPointClick?.onItemPointClick(textview.text.toString())
                }
            }

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int):RecyclerView.ViewHolder {
        return MHolder(LayoutInflater.from(context).inflate(R.layout.item_choose_medicine,parent,false))
    }

    inner class MHolder(view: View): RecyclerView.ViewHolder(view)

    interface OnItemPointClick{
        fun onItemPointClick(text:String)
    }
    fun setOnItemPointClick(itemPointClick: OnItemPointClick){
        this.itemPointClick=itemPointClick
    }

    private fun dp2px(dpValue: Int): Int{
        return (dpValue*(context.resources.displayMetrics.density)+0.5f).toInt()
    }
}